package me.alex.lifecycledemo;

import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * ================================================
 * Description:
 * <p>
 * Created by Alex on 2021/12/30
 * <p>
 * 页面内容介绍: 模拟业务发送或者接收,初始化后每3秒log一次
 * 便于区分生命周期使用log.i   运行使用log.e
 * <p>
 * ================================================
 */
public class Lifecycle1 implements LifecycleObserver {
    private static final String TAG = Lifecycle1.class.getSimpleName();
    Disposable dis;
    boolean isRun = true;//是否运行  页面暂停的时候不log

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void init() {
        Log.i(TAG, "ON_CREATE");
        Log.i(TAG, "串口打开");
        dis = Observable.interval(3, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (isRun) {
                            Log.e(TAG, "模拟运行,每秒一次");
                        }
                    }
                });
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void start() {
        Log.i(TAG, "ON_START");
        isRun = true;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void resume() {
        Log.i(TAG, "ON_RESUME");
        isRun = true;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void pause() {
        Log.i(TAG, "ON_PAUSE");
        isRun = false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void stop() {
        Log.i(TAG, "ON_STOP");
        isRun = false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void destroy() {
        Log.i(TAG, "ON_DESTROY");
        if (dis != null) {
            dis.dispose();
            Log.i(TAG, "串口关闭");
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void any(LifecycleOwner owner) {
        Log.i(TAG, "ON_ANY --- " + owner.getLifecycle().getCurrentState());
    }
}
